import React, { useState, useEffect } from 'react'
import { Search, X, FileText, Image as ImageIcon, FileSpreadsheet, File as FileIcon } from 'lucide-react'
import type { Attachment } from '@/types/work'
import { getAssessmentPlanAttachments, getAttachmentFile } from '@/api/work'
import { showMessage } from '@/components/common/MessageTip'
import { getBaseURL } from '@/utils/utils'

interface ExistingAttachmentSelectorProps {
  isOpen: boolean
  onClose: () => void
  onSelect: (attachments: Attachment[]) => void
  assessmentPlanId: string
  currentAttachments: Attachment[]
}

const ExistingAttachmentSelector: React.FC<ExistingAttachmentSelectorProps> = ({
  isOpen,
  onClose,
  onSelect,
  assessmentPlanId,
  currentAttachments
}) => {
  const [allAttachments, setAllAttachments] = useState<Attachment[]>([])
  const [filteredAttachments, setFilteredAttachments] = useState<Attachment[]>([])
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [searchTerm, setSearchTerm] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [fileTypeFilter, setFileTypeFilter] = useState<'all' | 'image' | 'file'>('all')

  // 加载所有附件
  useEffect(() => {
    const loadAttachments = async () => {
      if (!isOpen || !assessmentPlanId) return
      
      setIsLoading(true)
      try {
        const attachments = await getAssessmentPlanAttachments(assessmentPlanId)
        
        // 过滤掉当前已经添加的附件
        const currentAttachmentIds = new Set(currentAttachments.map(a => a.id))
        const availableAttachments = attachments.filter(a => !currentAttachmentIds.has(a.id))
        
        setAllAttachments(availableAttachments)
        setFilteredAttachments(availableAttachments)
      } catch (error) {
        console.error('加载附件失败:', error)
        showMessage('error', '加载附件列表失败', {
          position: 'top-right',
          autoClose: 3000
        })
      } finally {
        setIsLoading(false)
      }
    }

    loadAttachments()
  }, [isOpen, assessmentPlanId, currentAttachments])

  // 搜索和类型过滤
  useEffect(() => {
    let result = allAttachments
    
    // 按文件类型过滤
    if (fileTypeFilter === 'image') {
      result = result.filter(a => a.type && a.type.startsWith('image/'))
    } else if (fileTypeFilter === 'file') {
      result = result.filter(a => !a.type || !a.type.startsWith('image/'))
    }
    
    // 按搜索词过滤
    if (searchTerm.trim() !== '') {
      const term = searchTerm.toLowerCase()
      result = result.filter(a => a.name.toLowerCase().includes(term))
    }
    
    setFilteredAttachments(result)
  }, [searchTerm, fileTypeFilter, allAttachments])

  // 选择/取消选择附件
  const toggleAttachment = (attachmentId: string) => {
    setSelectedIds(prev => {
      const newSet = new Set(prev)
      if (newSet.has(attachmentId)) {
        newSet.delete(attachmentId)
      } else {
        newSet.add(attachmentId)
      }
      return newSet
    })
  }

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedIds.size === filteredAttachments.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(filteredAttachments.map(a => a.id)))
    }
  }

  // 确认选择
  const handleConfirm = () => {
    const selectedAttachments = allAttachments.filter(a => selectedIds.has(a.id))
    onSelect(selectedAttachments)
    handleClose()
  }

  // 关闭并重置状态
  const handleClose = () => {
    setSelectedIds(new Set())
    setSearchTerm('')
    setFileTypeFilter('all')
    onClose()
  }

  // 获取文件图标
  const getFileIcon = (type: string) => {
    if (type.startsWith('image/')) {
      return <ImageIcon className="w-5 h-5" />
    } else if (type.includes('pdf')) {
      return <FileText className="w-5 h-5 text-red-500" />
    } else if (type.includes('sheet') || type.includes('excel')) {
      return <FileSpreadsheet className="w-5 h-5 text-green-600" />
    } else if (type.includes('word') || type.includes('document')) {
      return <FileText className="w-5 h-5 text-blue-600" />
    }
    return <FileIcon className="w-5 h-5 text-gray-500" />
  }

  // 格式化文件大小
  const formatSize = (size: number): string => {
    if (size < 1024) {
      return `${size} B`
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(1)} KB`
    } else {
      return `${(size / (1024 * 1024)).toFixed(1)} MB`
    }
  }

  // 处理附件点击（预览/下载）
  const handleAttachmentClick = async (attachment: Attachment, e: React.MouseEvent) => {
    e.stopPropagation()
    
    try {
      const blob = await getAttachmentFile(attachment.id)
      const url = URL.createObjectURL(blob)
      
      if (attachment.type && attachment.type.startsWith('image/')) {
        window.open(url, '_blank', 'noopener,noreferrer')
      } else {
        const link = document.createElement('a')
        link.href = url
        link.download = attachment.name
        document.body.appendChild(link)
        link.click()
        link.remove()
      }
      setTimeout(() => URL.revokeObjectURL(url), 1000)
    } catch (error) {
      console.error('获取文件失败:', error)
      showMessage('error', '文件获取失败', {
        position: 'top-right',
        autoClose: 3000
      })
    }
  }

  if (!isOpen) return null

  return (
    <div 
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60] p-4"
      onClick={handleClose}
    >
      <div 
        className="bg-white dark:bg-slate-900 rounded-lg shadow-xl w-full max-w-3xl max-h-[80vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-slate-700">
          <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
            选择已上传的附件
          </h3>
          <button
            type="button"
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 搜索栏和筛选 */}
        <div className="p-4 border-b border-gray-200 dark:border-slate-700 space-y-3">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="搜索文件名..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100"
            />
          </div>
          
          {/* 文件类型筛选 */}
          <div className="flex space-x-2">
            <button
              type="button"
              onClick={() => setFileTypeFilter('all')}
              className={`flex items-center px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
                fileTypeFilter === 'all'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-slate-700'
              }`}
            >
              <FileIcon className="w-4 h-4 mr-1.5" />
              全部 ({allAttachments.length})
            </button>
            <button
              type="button"
              onClick={() => setFileTypeFilter('image')}
              className={`flex items-center px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
                fileTypeFilter === 'image'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-slate-700'
              }`}
            >
              <ImageIcon className="w-4 h-4 mr-1.5" />
              图片 ({allAttachments.filter(a => a.type && a.type.startsWith('image/')).length})
            </button>
            <button
              type="button"
              onClick={() => setFileTypeFilter('file')}
              className={`flex items-center px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${
                fileTypeFilter === 'file'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-slate-700'
              }`}
            >
              <FileText className="w-4 h-4 mr-1.5" />
              文件 ({allAttachments.filter(a => !a.type || !a.type.startsWith('image/')).length})
            </button>
          </div>
        </div>

        {/* 附件列表 */}
        <div className="flex-1 overflow-y-auto p-4">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-gray-500 dark:text-gray-400">加载中...</div>
            </div>
          ) : filteredAttachments.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12">
              <FileIcon className="w-16 h-16 text-gray-300 dark:text-gray-600 mb-4" />
              <p className="text-gray-500 dark:text-gray-400">
                {allAttachments.length === 0 ? '暂无可选择的附件' : '未找到匹配的附件'}
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {/* 全选选项 */}
              {filteredAttachments.length > 1 && (
                <div className="flex items-center p-3 bg-gray-50 dark:bg-slate-800 rounded-lg">
                  <input
                    type="checkbox"
                    checked={selectedIds.size === filteredAttachments.length && filteredAttachments.length > 0}
                    onChange={toggleSelectAll}
                    className="w-4 h-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500"
                  />
                  <span className="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                    全选 ({filteredAttachments.length})
                  </span>
                </div>
              )}

              {/* 附件列表项 */}
              {filteredAttachments.map((attachment) => (
                <div
                  key={attachment.id}
                  className={`flex items-center p-3 rounded-lg border-2 transition-all cursor-pointer ${
                    selectedIds.has(attachment.id)
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-200 dark:border-slate-700 hover:border-gray-300 dark:hover:border-slate-600 bg-white dark:bg-slate-800'
                  }`}
                  onClick={() => toggleAttachment(attachment.id)}
                >
                  <input
                    type="checkbox"
                    checked={selectedIds.has(attachment.id)}
                    onChange={() => {}}
                    className="w-4 h-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500"
                  />
                  
                  <div className="ml-3 flex-1 min-w-0 flex items-center">
                    {/* 文件图标/缩略图 */}
                    <div className="flex-shrink-0 h-12 w-12 rounded bg-gray-100 dark:bg-slate-700 flex items-center justify-center">
                      {attachment.type && attachment.type.startsWith('image/') ? (
                        <img 
                          src={`${getBaseURL()}/attachments/${attachment.id}`} 
                          alt="" 
                          className="h-full w-full object-cover rounded"
                        />
                      ) : (
                        getFileIcon(attachment.type)
                      )}
                    </div>

                    {/* 文件信息 */}
                    <div className="ml-3 min-w-0 flex-1">
                      <p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                        {attachment.name}
                      </p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        {formatSize(attachment.size)}
                      </p>
                    </div>

                    {/* 预览/下载按钮 */}
                    <button
                      type="button"
                      onClick={(e) => handleAttachmentClick(attachment, e)}
                      className="ml-2 px-3 py-1 text-xs text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors"
                    >
                      {attachment.type && attachment.type.startsWith('image/') ? '预览' : '下载'}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200 dark:border-slate-700">
          <span className="text-sm text-gray-600 dark:text-gray-400">
            已选择: {selectedIds.size} 个附件
          </span>
          <div className="flex space-x-3">
            <button
              type="button"
              onClick={handleClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-slate-800 border border-gray-300 dark:border-slate-600 rounded-md hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors"
            >
              取消
            </button>
            <button
              type="button"
              onClick={handleConfirm}
              disabled={selectedIds.size === 0}
              className={`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${
                selectedIds.size === 0
                  ? 'bg-gray-300 dark:bg-gray-700 cursor-not-allowed'
                  : 'bg-blue-600 hover:bg-blue-700'
              }`}
            >
              确认添加 ({selectedIds.size})
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ExistingAttachmentSelector

